package com.multimedia.scala.euler

import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer
/*
The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)
 */
object Asd36 {
  def main(args : Array[String]) : Unit = {
    @tailrec
    def generate2(curDigit: Int = 1, maxDigit: Int = 1023, buf: ListBuffer[Int] = ListBuffer[Int](1)): ListBuffer[Int] = {
      if (curDigit>maxDigit) buf
      else {
        var str = curDigit.toBinaryString
        val str2 = str.reverse
        buf+=java.lang.Integer.parseInt(str+str2, 2)
        if (2*curDigit<maxDigit) {
          buf+=java.lang.Integer.parseInt(str+"0"+str2, 2)
          buf+=java.lang.Integer.parseInt(str+"1"+str2, 2)
        }
        generate2(curDigit+1, maxDigit, buf)
      }
    }
    @tailrec
    def generate10(curDigit: Int = 1, maxDigit: Int = 999, buf: ListBuffer[Int] = ListBuffer[Int](1, 2, 3, 4, 5, 6, 7, 8, 9)): ListBuffer[Int] = {
      if (curDigit>maxDigit) buf
      else {
        val str = curDigit.toString()
        val str2 = str.reverse
        buf+=(str+str2).toInt
        if (10*curDigit<maxDigit) {
          (0 to 9).foreach(x=>{buf+=(str+x.toString+str2).toInt})
        }
        generate10(curDigit+1, maxDigit, buf)
      }
    }
    //println(generate10().size)
    //println(generate2().size)
    //println(generate10().toSet - generate2().toSet)
    var set2 = generate2().toSet[Int]
    var rez = generate10().toSet.filter(x=>set2.contains(x))
    println(rez.sum)
  }
}
